package com.eunion.boot.security;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import com.eunion.boot.spring.LocaleMessageSourceService;
import com.eunion.boot.spring.SpringUtil;

/**
 * 实现自定义的WebAuthenticationDetails
 * 该类提供了获取用户登录时携带的额外信息的功能，默认实现WebAuthenticationDetails提供了remoteAddress与sessionId信息。
 * 开发者可以通过Authentication的getDetails()获取WebAuthenticationDetails。
 * 编写自定义类CustomWebAuthenticationDetails继承自WebAuthenticationDetails，添加 token字段 
 * 
 * @since 2017年2月5日
 */
public class SysWebAuthenticationDetails extends WebAuthenticationDetails {

	private static final long serialVersionUID = 6975601077710753878L;

	private String varifyMsg;

	private HttpServletRequest request;//save request , to get LocaleMessage of login 

	public SysWebAuthenticationDetails(HttpServletRequest request) {
		super(request);
		this.request = request;
		//		LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
		String vfCode = request.getParameter("vcode");
		if (StringUtils.isBlank(vfCode) || vfCode.length() != 4) {
			LocaleMessageSourceService localeMessageSourceService = SpringUtil.getBean(LocaleMessageSourceService.class);
			varifyMsg = localeMessageSourceService.getMessage(request, "sys.login.invalidateVarifyCode");//请输入合法的验证码
			return;
		}

		Object code = request.getSession().getAttribute("_vcode");
		if (code == null || StringUtils.isBlank(code.toString()) || code.toString().length() != 4) {
			LocaleMessageSourceService localeMessageSourceService = SpringUtil.getBean(LocaleMessageSourceService.class);
			varifyMsg = localeMessageSourceService.getMessage(request, "sys.login.VarifyCodeExpire");//验证码已过期
			return;
		}
		if (!vfCode.equalsIgnoreCase(code.toString())) {
			LocaleMessageSourceService localeMessageSourceService = SpringUtil.getBean(LocaleMessageSourceService.class);
			varifyMsg = localeMessageSourceService.getMessage(request, "sys.login.VarifyCodeError");//验证码输入错误
			return;
		}

	}

	public String getVarifyMsg() {
		return varifyMsg;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

}
